package org.example.controller;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.example.bean.LoginUser;
import org.example.bean.Zh_user;
import org.example.service.IZHUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 增删改查
@Slf4j
@RestController
public class CrudController {

    @Autowired
    private IZHUserService zhUserService;

    /**
     * 登录
     * @param user
     * @param response
     * @param session
     * @param model
     * @return
     */
    @PostMapping("/login")
    public Map<String, String> gotoLogin(@RequestBody LoginUser user, HttpServletResponse response, HttpSession session, Model model) {
        String userName = user.getUserName();
        String password = user.getPassWord();
        Map<String, String> result = new HashMap<>();
        // 判断传入了用户名和密码
        if(StringUtils.hasLength(userName) && StringUtils.hasLength(password)) {
            //把登陆成功的用户保存起来
            session.setAttribute("userInfo", user);

            // 把cookie写道浏览器上
            Cookie cookie = new Cookie("user", user.getUserName());
            cookie.setHttpOnly(true); // 设置HttpOnly属性
            cookie.setPath("/"); // 设置cookie的有效路径
            cookie.setMaxAge(7 * 24 * 60 * 60); // 7天过期
            response.addCookie(cookie);

            System.out.println(user);
            result.put("code", "0");
            result.put("msg", "登录成功");
        } else {
            result.put("code", "10001");
            result.put("msg", "登录失败，请输入账号名密码！");
        }
        return result;
    }

    @PostMapping("/setData")
    public String setData(@RequestBody LoginUser user) {
        String userName = user.getUserName();
        String password = user.getPassWord();
        // 判断传入了用户名和密码
        JSONObject res = new JSONObject();
        if(StringUtils.hasLength(userName) && StringUtils.hasLength(password)) {
            Date now = new Date();
            String timeStr = DateUtils.format(now, "yyyy-MM-dd hh:mm:ss");
            res = zhUserService.addUser(new Zh_user(userName, password, timeStr, timeStr));
        }
        if(!res.containsKey("code") || res.get("code").equals("100")) {
            res.put("msg", "数据插入失败");
        } else {
            res.put("msg", "数据插入成功");
        }
        return res.toString();
    }

    @PostMapping("deleteUser")
    public JSONObject deleteUser(@RequestBody Map<String, String> info) {
        return zhUserService.deleteUser(info.get("userId"));
    }

    @GetMapping("getAllUser")
    public JSONObject getAllUser() {
        JSONObject jsonObject = new JSONObject();
        List<Map> users = zhUserService.getAllUser();
        // 把时间转换为 yyyy-MM-dd hh:mm:ss 格式
        for(Map user: users) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String str = dateFormat.format(user.get("createdAt"));
//            String str = convertTimestampToString((Timestamp) user.get("createdAt"));
            user.put("createdAt", str);
        }
        jsonObject.put("code", "0");
        jsonObject.put("res", users);
        return jsonObject;
    }

    public static String convertTimestampToString(Timestamp timestamp) {
        Instant instant = timestamp.toInstant();
        ZonedDateTime zdt = instant.atZone(ZoneId.of("UTC"));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm");
        return zdt.format(formatter);
    }
    public static String convertWithExceptionHandling(String input) {
        try {
            // 非空校验
            if (input == null || input.isEmpty()) {
                return input;
            }

            // 解析时间（兼容带时区的ISO格式）
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(input);

            // 定义目标格式（12小时制）
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

            // 格式化输出
            return zonedDateTime.format(outputFormatter);

      } catch (Exception e) {
            log.info("时间转换发生错误", e);
            return input;
        }
    }

    @PostMapping("upload")
    public String upload(@RequestPart("file") MultipartFile file) throws JSONException, IOException {
        JSONObject jsonObject = new JSONObject();
        if(!file.isEmpty()){
            String rootPath = System.getProperty("user.dir");
            File path = new File(rootPath, "src/main/resources/static/uploadFiles");
            //如果没有文件夹则创建
            if(!path.exists()) {
                path.mkdirs();
            }

            //保存到文件服务器，OSS服务器
            String originalFilename = file.getOriginalFilename();
            File filePath = null;
            if (originalFilename != null) {
                filePath = new File(path, originalFilename);
                file.transferTo(filePath);
                jsonObject.put("code", "0");
                jsonObject.put("msg", "文件上传成功");
                jsonObject.put("url", "http://localhost:8888/icbc/static/uploadFiles/" + originalFilename);
            }
        } else {
            jsonObject.put("code", "10003");
            jsonObject.put("msg", "文件上传失败");
        }

        return jsonObject.toString();
    }

}
